﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SettlementObject : MonoBehaviour
{
    Creature _caster;
    Action<SettlementObject, List<Creature>> _hitCallback;

    List<Creature> hitList= new List<Creature>();
    internal void Init(Creature caster, int radius, Action<SettlementObject,List<Creature>> hitCallback)
    {
        _caster = caster;
        _hitCallback = hitCallback;

        var collider=gameObject.GetComponent<CapsuleCollider>();
        collider.radius = radius;
        collider.isTrigger = true;
        collider.enabled = true;

        var rig = gameObject.AddComponent<Rigidbody>();
        rig.useGravity = false;

        MonoManager.GetInstance().StartCoroutine(onWaitAndHit());
    }

    private IEnumerator onWaitAndHit()
    {
        yield return new WaitForFixedUpdate();//等待物理关键帧更新后再执行，避免UPdate更新帧缺失
        onHitEnd();
    }
    
    private void onHitEnd()
    {
        if (_hitCallback!=null)
        {
            _hitCallback(this,hitList);
        }
    }

    private void OnTriggerEnter(Collider other)
    {
      
        var creature=other.gameObject.GetComponent<Creature>();
        if (creature == null) { return; }
        if (creature == _caster) { return; }
        if (!creature.CanBeAttack(_caster)) { return; }
        hitList.Add(creature);
    }
}
